package com.suns.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class CookieUtil {

    private static final String AES_KEY = "0123456789abcdef"; // AES密钥（长度为16，24或32）
    private static final String AES_IV = "0123456789abcdef"; // AES初值向量（与密钥长度相等）

    // 加密函数
    public static String encrypt(String plainText, String aesKey) throws Exception {
        byte[] keyBytes = AES_KEY.getBytes(StandardCharsets.UTF_8);
        byte[] ivBytes = AES_IV.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(cipherText);
    }

    // 解密函数
    public static String decrypt(String cipherText, String cookieKey) throws Exception {
        byte[] keyBytes = AES_KEY.getBytes(StandardCharsets.UTF_8);
        byte[] ivBytes = AES_IV.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] cipherData = Base64.getDecoder().decode(cipherText);
        byte[] plainData = cipher.doFinal(cipherData);
        return new String(plainData, StandardCharsets.UTF_8);
    }
}